﻿using AutoMapper;
using Ducu.BLL.Entity;
using Ducu.GLB.Global;
using Ducu.SRV.ProdService.ViewModelMap;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using Global.Core.ExtensionMethod;

namespace Ducu.SRV.ProdService
{
    public class BaseService
    {
        private RepoFactory _repoFactory;
        protected RepoFactory repoFactory
        {
            get
            {
                _repoFactory = _repoFactory ?? new RepoFactory();
                return _repoFactory;
            }
        }

        static BaseService()
        {
            createMap();
        }

        public static void EndSession()
        {
            RepoFactory.EndSession();
        }

        /// <summary>
        /// try to get the user ID from the cookie
        /// </summary>
        /// <returns>user entity</returns>
        protected User getCurrentUser()
        {
            var Context = HttpContext.Current;
            string key = CookieName.USER_ID;

            //use http context directly for performance improvement
            if (Context.Items[key] != null)
            {
                return (User)Context.Items[key];
            }

            var userIdentity = Context.Request.Cookies[key];
            if (userIdentity == null)
            {
                return null;
            }

            try
            {
                //try to get from cookie
                int userId = Convert.ToInt32(userIdentity.Values[0]);
                string encryptInfo = userIdentity.Values[1];

                if (string.IsNullOrEmpty(encryptInfo))
                {
                    string message = string.Format
                        ("cookie for {0}={1} has no encryption.",
                        key, userId);
                    throw new Exception(message);
                }

                User currentUser = repoFactory.Get<User>(userId);
                if (currentUser != null)
                {
                    if (currentUser.RegisterInfo.AuthCode.Md5Encypt() != encryptInfo)
                    {

                        string message = string.Format
                            ("cookie for {0}={1} has wrong encryption.", key, userId);
                        throw new Exception(message);
                    }

                    //use http context directly for performance improvement
                    Context.Items[key] = currentUser;
                }

                return currentUser;
            }
            catch (System.Exception e)
            {
                //TODO: workaround for the e.Message throw out exceptions.
                while (e.InnerException != null) e = e.InnerException;

                //TODO: where? how?
                new LogService().Off();
                Context.Items[key] = null;

                //TODO: probably need more information later.
                var log = log4net.LogManager.GetLogger("KnownError");
                log.Error(e.Message);

                //throw;
                return null;
            }

        }

        protected bool isCurrentUser(User user)
        {
            if (user == null || getCurrentUser() == null)
            {
                return false;
            }
            return getCurrentUser().Id == user.Id;
        }

        private static void createMap()
        {
#if DEBUG
            Mapper.AssertConfigurationIsValid();
#endif
            LogOnModelMap.Init();
            MessageModelMap.Init();
            PlanModelMap.Init();
            ProfileModelMap.Init();
            RegisterModelMap.Init();
            SharedModelMap.Init();
            TaskModelMap.Init();
            UserModelMap.Init();
        }
    }
}

